package com.quan.common.core.utils;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import org.springframework.format.Formatter;

public class DateFormatConversion implements Formatter<Date> {

	private String pattern = "yyyy-MM-dd";

	@Override
	public String print(Date date, Locale locale) {
		if (date == null) {
			return "";
		}
		return getDateFormat(locale).format(date);
	}

	@Override
	public Date parse(String formatted, Locale locale) throws ParseException {
		System.out.println(formatted);
		if (formatted.length() == 0) {
			return null;
		}
		if (formatted.length() == 8) {
			pattern = "HH:mm:ss";
		} else if (formatted.length() == 10) {
			pattern = "yyyy-MM-dd";
		} else {
			pattern = "yyyy-MM-dd HH:mm:ss";
		}
		return getDateFormat(locale).parse(formatted);
	}

	protected DateFormat getDateFormat(Locale locale) {
		DateFormat dateFormat = new SimpleDateFormat(this.pattern, locale);
		dateFormat.setLenient(false);
		return dateFormat;
	}

}
